/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.javamail.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Holds mail messages before being sent.
 *
 * @author Jose Noheda
 * @since 1.0
 */
public class MessageQueue {

    private static final int CAPACITY = 50;

    /**
     * Default size for retrieving operations.
     */
    public static final int BATCH_SIZE = 10;

    private BlockingQueue<MimeMessage> messages;

    /**
     * Creates a new queue with an initial capacity fo 50
     */
    public MessageQueue() {
        this(CAPACITY);
    }

    /**
     * Creates a new queue with a specific capacity.
     *
     * @param capacity a positive integer (otherwise fallsback to the default value of 50)
     */
    public MessageQueue(int capacity) {
        this.messages = new ArrayBlockingQueue<MimeMessage>(capacity > 0 ? capacity : CAPACITY);
    }

    /**
     * Adds a new message to the queue of pending ones. If the capacity is exceeded
     * this operation is blocking.
     *
     * @param message any
     * @return true if the message has been accepted
     */
    public boolean enqueue(MimeMessage message) {
        return message != null ? messages.offer(message) : false;
    }

    /**
     * Retrieves a number of stored messages for processing.
     *
     * @param number a positive number (otherwise the default value)
     * @return a non null collection
     */
    public Collection<MimeMessage> take(int number) {
        int total = number > 0 ? number : BATCH_SIZE;
        Collection<MimeMessage> elements = new ArrayList<MimeMessage>(total);
        messages.drainTo(elements, total);
        return Collections.unmodifiableCollection(elements);
    }

}
